package org.lee.openoffice.util;

import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class StreamUtil {

    private static final String DEFAULT_EXT = "pdf";

    private static final int OPENOFFICE_PORT = 8100;

    /**
     * 网络文件转office流
     *
     * @param fileUrl 文件url
     * @param ext     后缀
     * @return
     * @throws Exception
     */
    public static InputStream fromNetFile(String fileUrl, String ext) throws Exception {
        URL url = new URL(fileUrl);
        URLConnection conn = url.openConnection();
        conn.connect();
        HttpURLConnection http = (HttpURLConnection) conn;
        int code = http.getResponseCode();
        if (code == HttpURLConnection.HTTP_OK) {
            InputStream is = conn.getInputStream();
            return inputStream2Office(is, ext);
        }
        return null;
    }

    /**
     * 本地文件转office流
     *
     * @param fileName 文件路径
     * @param ext      后缀
     * @return
     * @throws FileNotFoundException
     */
    public static InputStream fromFile(String fileName, String ext) throws FileNotFoundException {
        File file = new File(fileName);
        InputStream is = new FileInputStream(file);
        return inputStream2Office(is, ext);
    }

    /**
     * 普通流转换为Office流
     *
     * @param inputStream 源文件流
     * @param ext         源文件后缀
     * @return 转换后office流
     */
    public static InputStream inputStream2Office(InputStream inputStream, String ext) {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            OpenOfficeConnection conn = new SocketOpenOfficeConnection(OPENOFFICE_PORT);
            conn.connect();
            DocumentConverter converter = new StreamOpenOfficeDocumentConverter(conn);
            DefaultDocumentFormatRegistry formatRegistry = new DefaultDocumentFormatRegistry();
            DocumentFormat targetFormat = formatRegistry.getFormatByFileExtension(DEFAULT_EXT);
            DocumentFormat sourceFormat = formatRegistry.getFormatByFileExtension(ext);
            converter.convert(inputStream, sourceFormat, out, targetFormat);
            conn.disconnect();
            return new ByteArrayInputStream(out.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
